<template>
    <div class="login-register-container">
        <Vcode :show="isShow" @success="onSuccess" @close="onClose" />
        <!-- 背景层 -->
        <div class="background"></div>
        <div class="form-container">
            <el-tabs v-model="activeTab" @tab-click="handleTabClick">
                <el-tab-pane label="登录" name="login"></el-tab-pane>
                <el-tab-pane label="注册" name="register"></el-tab-pane>

            </el-tabs>
            <div v-if="activeTab === 'login'" class="form-wrapper">
                <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" label-width="80px">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="loginForm.username"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="loginForm.password" type="password"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleLogin">登录</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div v-else class="form-wrapper">
                <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef" label-width="80px">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="registerForm.username"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="registerForm.password" type="password"></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码" prop="rePassword">
                        <el-input v-model="registerForm.rePassword" type="password"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleRegister">注册</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <a :href="giteeAuthUrl" class="el-button el-button--primary">Gitee登录</a>
        </div>
    </div>
</template>

<script setup>

import { loginAPI, registerAPI } from '@/api/user';
import { ElMessage } from 'element-plus';
import { ref, reactive } from 'vue';
import Vcode from "vue3-puzzle-vcode";
import { useUserStore } from '@/stores/userStore';
import { useChatStore } from '@/stores/chat';
const giteeAuthUrl = ref('http://localhost:8080/user/render')
const flag = ref(false);
import { useRoute, useRouter } from 'vue-router';
const isShow = ref(false);
const chatStore = useChatStore()
const onShow = () => {
    isShow.value = true;
};

const onClose = () => {
    isShow.value = false;
};

const onSuccess = () => {
    flag.value = true;
    onClose(); // 验证成功，手动关闭模态框
};

// 定义当前激活的标签页
const activeTab = ref('login');

// 登录表单数据
const loginForm = reactive({
    username: '',
    password: '',
    chatDto: {
        question: '',
        answer: '',
        memoryId: '',
        filePath: ''
    }
});

// 登录表单验证规则
const loginRules = reactive({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
    ]
});

// 注册表单数据
const registerForm = reactive({
    username: '',
    password: '',
    rePassword: '',
    chatDto: {
        question: '',
        answer: '',
        memoryId: '',
        filePath: ''
    }
});

// 注册表单验证规则
const registerRules = reactive({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
    ],
    rePassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== registerForm.password) {
                    callback(new Error('两次输入的密码不一致'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ]
});

// 登录表单引用
const loginFormRef = ref(null);
// 注册表单引用
const registerFormRef = ref(null);

// 处理标签页切换（修改后）
const handleTabClick = (tab) => {
    const tabName = tab.paneName || tab.props.name; // 兼容不同版本的 Element Plus
    if (tabName === 'login') {
        // 切换到登录时清空注册表单
        registerForm.username = ''
        registerForm.password = ''
        registerForm.rePassword = ''
        // registerFormRef.value?.resetFields()
    } else if (tabName === 'register') {
        // 切换到注册时清空登录表单
        loginForm.username = ''
        loginForm.password = ''
        // loginFormRef.value?.resetFields()
    }
    activeTab.value = tabName
}


const userStore = useUserStore()
// 处理登录逻辑
const handleLogin = async () => {
    if (!flag.value) {
        onShow();
        if (!flag.value) {
            ElMessage.warning("请完成验证")
            return
        }
    }
    const isValid = await new Promise((resolve) => {
        loginFormRef.value.validate((valid) => {
            resolve(valid);
        });
    });
    if (isValid) {
        try {
            flag.value = !flag.value
            const response = await loginAPI(loginForm);
            userStore.setUser(response.data)
            userStore.setToken(response.data.token)
            console.log('登录成功:', response.data);
            // 这里可以添加登录成功后的跳转逻辑
            goChat()
        } catch (error) {
            console.error('登录失败:', error);
        }
    }
};

// 处理注册逻辑
const handleRegister = async () => {
    if (!flag.value) {
        onShow();
        if (!flag.value) {
            ElMessage.warning("请完成验证")
            return
        }
    }
    const isValid = await new Promise((resolve) => {
        registerFormRef.value.validate((valid) => {
            resolve(valid);
        });
    });
    if (isValid) {
        try {
            flag.value = !flag.value
            const response = await registerAPI(registerForm);
            userStore.setUser(response.data)
            userStore.setToken(response.data.token)
            console.log('注册成功:', response.data);
            // 注册成功后切换到登录页
            //activeTab.value = 'login';
            goChat()
        } catch (error) {
            console.error('注册失败:', error);
        }
    }
};
const route = useRoute();
const router = useRouter();
const goChat = () => {
    const id = loginForm.chatDto.memoryId === '' ? registerForm.chatDto.memoryId : loginForm.chatDto.memoryId
    router.push({
        path: '/chat/' + id,
    });
}

const getChatDetails = () => {
    let chat = chatStore.getChat()
    console.log('chat', chat);
    if (chat) {
        loginForm.chatDto = chat
        registerForm.chatDto = chat
    }
}

getChatDetails()
</script>

<style scoped>
* {
    margin: 0;
    padding: 0;
}

.login-register-container {
    position: relative;
    width: 100vw;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
}

.background {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #71b7e6, #9b59b6);
    filter: blur(10px);
    z-index: -1;
}

.form-container {
    background-color: rgba(255, 255, 255, 0.9);
    border-radius: 10px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
    padding: 30px;
    width: 400px;
    animation: fadeIn 0.5s ease;
}

.form-wrapper {
    margin-top: 20px;
}

.el-tabs__item {
    font-size: 18px;
    font-weight: bold;
    color: #333;
}

.el-tabs__item.is-active {
    color: #9b59b6;
}

.el-form-item__label {
    font-size: 16px;
    color: #333;
}

.el-input__inner {
    border-radius: 5px;
}

.el-button {
    width: 100%;
    border-radius: 5px;
    font-size: 16px;
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(-20px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.form-container {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 16px;
    box-shadow:
        0 8px 32px rgba(0, 0, 0, 0.1),
        0 2px 8px rgba(0, 0, 0, 0.08),
        inset 0 1px 1px rgba(255, 255, 255, 0.3);
    padding: 40px 35px;
    width: 420px;
    backdrop-filter: blur(12px);
    border: 1px solid rgba(255, 255, 255, 0.4);
    position: relative;
    z-index: 1;
    transform: translateZ(0);
    transition:
        transform 0.3s ease,
        box-shadow 0.3s ease;
}

.form-container:hover {
    transform: translateY(-2px);
    box-shadow:
        0 12px 40px rgba(0, 0, 0, 0.15),
        0 4px 12px rgba(0, 0, 0, 0.1),
        inset 0 2px 2px rgba(255, 255, 255, 0.4);
}

/* 优化内部元素间距 */
.form-wrapper {
    margin: 25px 0 15px;
}

.el-tabs {
    margin-bottom: -10px;
}

/* 标签页样式微调 */
.el-tabs__item {
    font-size: 17px;
    letter-spacing: 0.5px;
    padding: 0 20px 15px;
    transition: color 0.2s ease;
}

.el-tabs__item.is-active {
    color: #7c5bf2;
    font-weight: 500;
}

.el-tabs__active-bar {
    background-color: #7c5bf2;
    height: 3px;
    border-radius: 2px;
}

/* 输入框精致化 */
.el-input__inner {
    border-radius: 8px;
    padding: 12px 15px;
    transition:
        border-color 0.3s ease,
        box-shadow 0.3s ease;
}

.el-input__inner:focus {
    border-color: #7c5bf2;
    box-shadow: 0 2px 6px rgba(124, 91, 242, 0.15);
}

/* 按钮精致化 */
.el-button {
    border-radius: 8px;
    padding: 13px 20px;
    font-size: 15px;
    letter-spacing: 0.5px;
    transition:
        transform 0.2s ease,
        box-shadow 0.2s ease;
}

.el-button:active {
    transform: scale(0.98);
}

.el-button--primary {
    background: linear-gradient(135deg, #7c5bf2, #6a4be0);
    border: none;
}

.el-button--primary:hover {
    box-shadow: 0 4px 12px rgba(124, 91, 242, 0.25);
}

/* Gitee 按钮样式 */
.el-button:not(.el-button--primary) {
    border: 1px solid #eee;
    color: #666;
}

.el-button:not(.el-button--primary):hover {
    background: rgba(0, 0, 0, 0.02);
}
</style>